// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

// 云函数入口函数
exports.main = async (event, context) => {
  const { openid, templateId, page, data } = event
  
  // 参数验证
  if (!openid || !templateId) {
    return {
      success: false,
      error: '缺少必要参数'
    }
  }
  
  try {
    // 发送订阅消息
    const result = await cloud.openapi.subscribeMessage.send({
      touser: openid,
      templateId: templateId,
      page: page || 'pages/index/index',
      data: data || {},
      miniprogramState: 'formal' // developer, trial, formal
    })
    
    // 记录发送结果
    await cloud.database().collection('notifications_log').add({
      data: {
        openid,
        templateId,
        page,
        data,
        result,
        success: true,
        createdAt: new Date()
      }
    })
    
    return {
      success: true,
      result
    }
  } catch (error) {
    // 记录错误
    await cloud.database().collection('notifications_log').add({
      data: {
        openid,
        templateId,
        page,
        data,
        error: error.message || JSON.stringify(error),
        success: false,
        createdAt: new Date()
      }
    })
    
    return {
      success: false,
      error: error.message || '发送订阅消息失败'
    }
  }
} 